package com.abc.cloud.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.abc.cloud.common.utils.UserHolder;
import com.abc.cloud.dto.im.ChatDetail;
import com.abc.cloud.entity.FileEntity;
import com.abc.cloud.entity.GroupEntity;
import com.abc.cloud.entity.UserEntity;
import com.abc.cloud.service.ChatDetailUserService;
import com.abc.cloud.service.ChatUserService;
import com.abc.cloud.vo.im.AdminUpdateChatDetailReq;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.abc.cloud.common.utils.PageUtil;
import com.abc.cloud.common.utils.Query;

import com.abc.cloud.dao.ChatDetailDao;
import com.abc.cloud.entity.ChatDetailEntity;
import com.abc.cloud.service.ChatDetailService;


@Service("chatDetailService")
public class ChatDetailServiceImpl extends ServiceImpl<ChatDetailDao, ChatDetailEntity> implements ChatDetailService {

    @Autowired
    private ChatDetailUserService chatDetailUserService;

    @Autowired
    private ChatUserService chatUserService;

    @Override
    public List<ChatDetail> queryPage(Map<String, Object> params) {
        Long chatId = Long.valueOf((String) params.get("id"));
        Long userId = UserHolder.getUser().getId();

        List<ChatDetailEntity> chatDetailEntityList = this.baseMapper.queryChatDetailUnreadById(chatId, userId, 2);
        List<ChatDetail> res = new ArrayList<>();
        for (ChatDetailEntity chatDetailEntity : chatDetailEntityList) {
            ChatDetail chatDetail = getChatDetail(chatDetailEntity);
            if (chatDetailEntity.getFileList() != null){
                chatDetail.setFileList(JSONUtil.toList(chatDetailEntity.getFileList(), FileEntity.class));
            }
            res.add(chatDetail);
        }

        // 清除未读消息
        if (chatDetailEntityList.size() != 0){
            List<Long> chatDetailIds = chatDetailEntityList.stream().map(ChatDetailEntity::getId).collect(Collectors.toList());
            chatDetailUserService.changeRead(chatDetailIds, userId, 1);
            chatUserService.changeReadCount(chatId, userId, 0);
        }


        return res;
    }

    @Override
    public void saveChatDetail(ChatDetailEntity chatDetailEntity) {
        this.baseMapper.saveChatDetail(chatDetailEntity);
    }




    private ChatDetail getChatDetail(ChatDetailEntity chatDetailEntity) {
        ChatDetail chatDetail = new ChatDetail();
        chatDetail.setChatId(chatDetailEntity.getChatId());
        chatDetail.setContent(chatDetailEntity.getContent());
        chatDetail.setCreateTime(DateUtil.format(chatDetailEntity.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        chatDetail.setFromAvatar(chatDetailEntity.getFromAvatar());
        chatDetail.setFromNickname(chatDetailEntity.getFromNickname());
        chatDetail.setFromUserId(chatDetailEntity.getFromUserId());
        chatDetail.setFromUsername(chatDetailEntity.getFromUsername());
        chatDetail.setToAvatar(chatDetailEntity.getToAvatar());
        chatDetail.setToNickname(chatDetailEntity.getToNickname());
        chatDetail.setToAvatar(chatDetailEntity.getToAvatar());
        chatDetail.setToUserId(chatDetailEntity.getToUserId());
        chatDetail.setToUsername(chatDetailEntity.getToUsername());
        return chatDetail;
    }

    @Override
    public PageUtil adminChatList(Map<String, Object> params) {
        QueryWrapper<ChatDetailEntity> groupEntityQueryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (key != null && !key.isEmpty()){
            groupEntityQueryWrapper.eq("username", key);
        }

        IPage<ChatDetailEntity> page = this.page(
                new Query<ChatDetailEntity>().getPage(params),
                groupEntityQueryWrapper
        );

        return new PageUtil(page);
    }

    @Override
    public void adminUpdateChat(AdminUpdateChatDetailReq adminUpdateChatDetailReq) {
        ChatDetailEntity chatDetailEntity = this.baseMapper.selectById(adminUpdateChatDetailReq.getId());
        BeanUtils.copyProperties(adminUpdateChatDetailReq, chatDetailEntity);
        this.baseMapper.updateById(chatDetailEntity);
    }

    @Override
    public void adminDeleteChat(List<Long> ids, Integer status) {
        this.baseMapper.deleteChatDetailByIds(ids, status);
    }
}